package com.nuo.backend.modules.test.interceptor;


import com.nuo.backend.common.threadlocal.SessionThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @description: TODO session拦截
* @author nuo
* @date 2022/11/21 12:40
* @version 1.0
*/
@Component
@Slf4j
public class SessionInterceptor implements HandlerInterceptor {

   @Autowired
   private SessionThreadLocal sessionThreadLocal;

   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       log.info("enter SessionInterceptor");
       log.info("sessionId: " + request.getSession().getId());
       sessionThreadLocal.set(request.getSession().getId());
       return true;
   }

   @Override
   public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
   }

   @Override
   public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       sessionThreadLocal.remove();
       HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
   }
}
